<template>
  <div class="system-user">
    <BaseList
      title="系统用户列表"
      :loading="loading"
      :data="tableData"
      :search-fields="searchFields"
      :pagination="pagination"
      :add-permission="['system:users:add']"
      :debounce-delay="300"
      @search="handleSearch"
      @reset="handleReset"
      @add="handleAdd"
      @update:pagination="handlePaginationChange"
    >
      <template #columns>
        <a-table-column title="头像" data-index="avatar" :width="80">
          <template #cell="{ record }">
            <div class="avatar-wrapper">
              <a-avatar :size="40" :image-url="record.avatar" />
            </div>
          </template>
        </a-table-column>
        <a-table-column title="账号" data-index="account" />
        <a-table-column title="昵称" data-index="name" />
        <a-table-column title="真实姓名" data-index="realName" />
        <a-table-column title="邮箱" data-index="email" />
        <a-table-column title="手机号" data-index="phone" />
        <a-table-column title="性别" data-index="sex">
          <template #cell="{ record }">
            <a-tag :color="record.sex === 1 ? 'arcoblue' : 'magenta'">
              {{ record.sex === 1 ? '男' : '女' }}
            </a-tag>
          </template>
        </a-table-column>
        <a-table-column title="状态" data-index="status">
          <template #cell="{ record }">
            <a-tag :color="record.status === 1 ? 'green' : 'red'">
              {{ record.status === 1 ? '正常' : '停用' }}
            </a-tag>
          </template>
        </a-table-column>
        <a-table-column title="创建时间" data-index="gmtCreate" />
        <a-table-column title="角色" data-index="roleName" />
        <a-table-column title="操作" align="center" :width="240">
          <template #cell="{ record }">
            <a-space>
              <BaseButton
                v-permission="'system:users:details'"
                type="outline"
                size="mini"
                @click="handleDetail(record)"
              >
                <template #icon>
                  <BaseIcon name="icon-eye" />
                </template>
                详情
              </BaseButton>
              <BaseButton
                v-permission="'system:users:edit'"
                type="outline"
                size="mini"
                @click="handleEdit(record)"
              >
                <template #icon>
                  <BaseIcon name="icon-edit" />
                </template>
                编辑
              </BaseButton>
              <BaseButton
                v-permission="'system:users:reset-password'"
                type="outline"
                size="mini"
                status="warning"
                @click="handleResetPassword(record)"
              >
                <template #icon>
                  <BaseIcon name="icon-lock" />
                </template>
                重置密码
              </BaseButton>
              <BaseButton
                v-permission="'system:users:normal-disable'"
                type="outline"
                size="mini"
                :status="record.status === 1 ? 'danger' : 'success'"
                @click="handleModifyStatus(record)"
              >
                <template #icon>
                  <BaseIcon name="icon-poweroff" v-if="record.status === 1" />
                  <BaseIcon name="icon-play-circle" v-else />
                </template>
                {{ record.status === 1 ? '停用' : '启用' }}
              </BaseButton>
              <BaseButton
                v-permission="'system:users:delete'"
                type="outline"
                size="mini"
                status="danger"
                :loading="loading"
                @click="handleDelete(record)"
              >
                <template #icon>
                  <BaseIcon name="icon-delete" />
                </template>
                删除
              </BaseButton>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </BaseList>

    <LoadingSpinner :visible="loading" text="加载中..." />

    <!-- 添加用户弹窗 -->
    <BaseForm
      v-model:visible="dialogVisible"
      :title="dialogTitle"
      :loading="loading"
      v-model="formData"
      :rules="rules"
      @cancel="handleCancel"
      @submit="handleSubmit"
    >
      <template #form-items>
        <a-form-item
          label="头像"
          field="avatar"
          :label-col-props="{ span: 24 }"
          :wrapper-col-props="{ span: 24 }"
        >
          <div class="flex justify-center">
            <upload-image
              v-model="formData.avatar"
              placeholder="点击上传头像"
              shape="circle"
              :width="80"
              :height="80"
              :accept="'image/*'"
            />
          </div>
        </a-form-item>

        <a-form-item
          label="账号"
          field="account"
          :label-col-props="{ span: 24 }"
          :wrapper-col-props="{ span: 24 }"
        >
          <a-input v-model="formData.account" placeholder="请输入账号" size="large" allow-clear />
        </a-form-item>

        <a-form-item
          label="密码"
          field="password"
          v-if="isAdd"
          :label-col-props="{ span: 24 }"
          :wrapper-col-props="{ span: 24 }"
        >
          <a-input-password
            v-model="formData.password"
            placeholder="请输入密码"
            size="large"
            allow-clear
          />
        </a-form-item>

        <a-form-item
          label="真实姓名"
          field="realName"
          :label-col-props="{ span: 24 }"
          :wrapper-col-props="{ span: 24 }"
        >
          <a-input
            v-model="formData.realName"
            placeholder="请输入真实姓名"
            size="large"
            allow-clear
          />
        </a-form-item>

        <a-form-item
          label="昵称"
          field="name"
          :label-col-props="{ span: 24 }"
          :wrapper-col-props="{ span: 24 }"
        >
          <a-input v-model="formData.name" placeholder="请输入昵称" size="large" allow-clear />
        </a-form-item>

        <a-form-item
          label="性别"
          field="sex"
          :label-col-props="{ span: 24 }"
          :wrapper-col-props="{ span: 24 }"
        >
          <a-radio-group v-model="formData.sex" size="large">
            <a-radio :value="1">男</a-radio>
            <a-radio :value="2">女</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item
          label="生日"
          field="birthday"
          :label-col-props="{ span: 24 }"
          :wrapper-col-props="{ span: 24 }"
        >
          <a-date-picker
            v-model="formData.birthday"
            value-format="YYYY-MM-DD"
            placeholder="请选择生日"
            size="large"
            style="width: 100%"
          />
        </a-form-item>

        <a-form-item
          label="手机号"
          field="phone"
          :label-col-props="{ span: 24 }"
          :wrapper-col-props="{ span: 24 }"
        >
          <a-input v-model="formData.phone" placeholder="请输入手机号" size="large" allow-clear />
        </a-form-item>

        <a-form-item
          label="邮箱"
          field="email"
          :label-col-props="{ span: 24 }"
          :wrapper-col-props="{ span: 24 }"
        >
          <a-input v-model="formData.email" placeholder="请输入邮箱" size="large" allow-clear />
        </a-form-item>

        <a-form-item
          label="角色"
          field="roleId"
          :label-col-props="{ span: 24 }"
          :wrapper-col-props="{ span: 24 }"
        >
          <a-select
            v-model="formData.roleId"
            placeholder="请选择角色"
            size="large"
            allow-clear
            allow-search
            :filter-option="false"
            :loading="roleLoading"
            @search="handleRoleSearch"
          >
            <a-option
              v-for="role in roleOptions"
              :key="role.boxId"
              :value="role.boxId"
              :label="role.boxName"
            />
          </a-select>
        </a-form-item>
      </template>
    </BaseForm>

    <!-- 详情弹窗 -->
    <a-modal v-model:visible="detailVisible" title="用户详情" :footer="false" :width="500">
      <div class="p-6">
        <!-- 头像区域 -->
        <div class="flex justify-center mb-8">
          <div class="relative">
            <a-avatar :size="88" :image-url="detailInfo.avatar" />
            <div
              class="absolute -bottom-1 left-1/2 -translate-x-1/2 px-3 py-1 bg-blue-500 rounded-full text-white text-xs max-w-[120px]"
            >
              <span class="block truncate">{{ detailInfo.name }}</span>
            </div>
          </div>
        </div>

        <!-- 基本信息区域 -->
        <div class="grid grid-cols-2 gap-6 mb-6">
          <div class="info-item">
            <div class="info-label">账</div>
            <div class="info-value">{{ detailInfo.account || '-' }}</div>
          </div>
          <div class="info-item">
            <div class="info-label">真实姓名</div>
            <div class="info-value">{{ detailInfo.realName || '-' }}</div>
          </div>
          <div class="info-item">
            <div class="info-label">邮箱</div>
            <div class="info-value">{{ detailInfo.email || '-' }}</div>
          </div>
          <div class="info-item">
            <div class="info-label">手机号</div>
            <div class="info-value">{{ detailInfo.phone || '-' }}</div>
          </div>
          <div class="info-item">
            <div class="info-label">角色</div>
            <div class="info-value">{{ detailInfo.roleName || '-' }}</div>
          </div>
        </div>

        <!-- 状态信息区域 -->
        <div class="flex gap-6 mb-8">
          <div
            class="flex-1 status-card"
            :class="detailInfo.sex === 1 ? 'bg-blue-50' : 'bg-pink-50'"
          >
            <BaseIcon
              name="icon-user"
              class="text-xl"
              :class="detailInfo.sex === 1 ? 'text-blue-500' : 'text-pink-500'"
            />
            <div class="mt-2">性别</div>
            <div
              class="text-lg font-medium"
              :class="detailInfo.sex === 1 ? 'text-blue-500' : 'text-pink-500'"
            >
              {{ detailInfo.sex === 1 ? '男' : '女' }}
            </div>
          </div>
          <div
            class="flex-1 status-card"
            :class="detailInfo.status === 1 ? 'bg-green-50' : 'bg-red-50'"
          >
            <BaseIcon
              name="icon-check-circle"
              class="text-xl"
              :class="detailInfo.status === 1 ? 'text-green-500' : 'text-red-500'"
            />
            <div class="mt-2">状态</div>
            <div
              class="text-lg font-medium"
              :class="detailInfo.status === 1 ? 'text-green-500' : 'text-red-500'"
            >
              {{ detailInfo.status === 1 ? '正常' : '停用' }}
            </div>
          </div>
        </div>

        <!-- 时间信息区域 -->
        <div class="bg-gray-50 rounded-lg p-4">
          <div class="text-sm text-gray-500 mb-3">系统信息</div>
          <div class="grid grid-cols-2 gap-4">
            <div class="time-item">
              <div class="time-label">创建时间</div>
              <div class="time-value">{{ detailInfo.gmtCreate || '-' }}</div>
            </div>
            <div class="time-item">
              <div class="time-label">创建人</div>
              <div class="time-value">{{ detailInfo.gmtCreateName || '-' }}</div>
            </div>
            <div class="time-item">
              <div class="time-label">更新时间</div>
              <div class="time-value">{{ detailInfo.gmtModified || '-' }}</div>
            </div>
            <div class="time-item">
              <div class="time-label">更新人</div>
              <div class="time-value">{{ detailInfo.gmtModifiedName || '-' }}</div>
            </div>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import BaseList from '@/components/BaseList.vue'
import LoadingSpinner from '@/components/LoadingSpinner.vue'
import { systemUserService } from '@/services/systemUser'
import type { SystemUsersResponse, SystemUsersPageParam } from '@/types/systemUser'
import { useNotification } from '@/composables/useNotification'
import { filterEmptyValue } from '@/utils/object'
import BaseButton from '@/components/BaseButton.vue'
import type { FormInstance } from '@arco-design/web-vue'
import { Modal } from '@arco-design/web-vue'
import type { SystemUsersRequest } from '@/types/systemUser'
import UploadImage from '@/components/UploadImage.vue'
import BaseForm from '@/components/BaseForm.vue'
import { defaultPassword } from '@/config'
import BaseIcon from '@/components/BaseIcon.vue'
import { getIcon } from '@/composables/useIcons'
import { roleService } from '@/services/systemRole'

const loading = ref(false)
const tableData = ref<SystemUsersResponse[]>([])
const notify = useNotification()

// 定义搜索字段
const searchFields = [
  {
    key: 'account',
    placeholder: '请输入账号',
    icon: getIcon('icon-search'),
  },
  {
    key: 'name',
    placeholder: '请输入昵称',
    icon: getIcon('icon-user'),
  },
]

// 分页信息
const pagination = ref({
  total: 0,
  current: 1,
  pageSize: 10,
})

// 表单相关
const formRef = ref<FormInstance>()
const dialogVisible = ref(false)
const dialogTitle = ref('新增用户')
const isAdd = ref(true)

// 表单数据
const formData = reactive<SystemUsersRequest>({
  systemUserId: '',
  account: '',
  password: '',
  name: '',
  realName: '',
  avatar: '',
  email: '',
  phone: '',
  birthday: '',
  sex: 1,
  status: 1,
  availableDrawCount: 0,
  roleId: '',
})

// 表单校验规则
const rules = {
  account: [
    { required: true, message: '请输入账号' },
    { minLength: 4, message: '账号长度不能小于4位' },
  ],
  password: [
    { required: true, message: '请输入密码' },
    { minLength: 6, message: '密码长度不能小于6位' },
  ],
  name: [
    { required: true, message: '请输入昵称' },
    { minLength: 2, message: '昵称长度不能小于2位' },
  ],
  email: [
    { required: true, message: '请输入邮箱' },
    {
      pattern: /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/,
      message: '请输入正确的邮箱格式',
    },
  ],
  phone: [
    { required: true, message: '请输入手机号' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式' },
  ],
  realName: [{ required: true, message: '请输入真实姓名' }],
  sex: [{ required: true, message: '请选择性别' }],
  roleId: [{ required: true, message: '请选择角色' }],
}

// 详情相关
const detailVisible = ref(false)
const detailInfo = ref<Partial<SystemUsersResponse>>({})

// 添加角色下拉框数据
const roleOptions = ref<{ boxId: string; boxName: string }[]>([])

// 在 script setup 中添加
const roleLoading = ref(false)

// 保存当前搜索条件
const currentSearchParams = ref<Partial<SystemUsersPageParam>>({})

/** 获取用户表数据 */
const fetchData = async (searchParams = {}) => {
  loading.value = true
  try {
    const params: SystemUsersPageParam = {
      pageNum: pagination.value.current,
      pageSize: pagination.value.pageSize,
      ...filterEmptyValue(searchParams),
    }

    const res = await systemUserService.getSystemUsersPage(params)
    tableData.value = res.list

    // 更新分页信息，确保所有必要的字段都被更新
    pagination.value = {
      ...pagination.value,
      current: res.pageNum, // 确保使用后端返回的当前页码
      total: res.total, // 设置总记录数
      pageSize: res.pageSize, // 确保使用后端返回的每页大小
    }
  } catch (error) {
    notify.error('获取用户列表失败')
    console.error('获取用户列表出错:', error)
  } finally {
    loading.value = false
  }
}

/** 搜索处理 */
const handleSearch = (form: Partial<SystemUsersPageParam>) => {
  pagination.value.current = 1
  currentSearchParams.value = form // 保存搜索条件
  fetchData(form)
}

/** 重置处理 */
const handleReset = () => {
  // 重置分页到第一页
  pagination.value.current = 1
  // 获取数据
  fetchData()
}

/** 新增用户 */
const handleAdd = () => {
  dialogVisible.value = true
  dialogTitle.value = '新增用户'
  isAdd.value = true
  resetForm()
}

/** 编辑用户 */
const handleEdit = async (record: SystemUsersResponse) => {
  try {
    loading.value = true
    const res = await systemUserService.getSystemUsersById(record.systemUserId)

    dialogVisible.value = true
    dialogTitle.value = '编辑用户'
    isAdd.value = false

    Object.assign(formData, {
      systemUserId: res.systemUserId,
      account: res.account,
      name: res.name,
      realName: res.realName,
      avatar: res.avatar,
      email: res.email,
      phone: res.phone,
      birthday: res.birthday,
      sex: res.sex,
      availableDrawCount: res.availableDrawCount,
      roleId: res.roleId,
    })
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : '获取用户详情失败'
    notify.error(errorMessage, {
      title: '操作失败',
    })
  } finally {
    loading.value = false
  }
}

/** 删除用户 */
const handleDelete = async (record: SystemUsersResponse) => {
  Modal.warning({
    title: '确认删除',
    content: `确定要删除用户 "${record.name}" 吗？`,
    okText: '确定',
    cancelText: '取消',
    hideCancel: false,
    async onOk() {
      try {
        loading.value = true
        await systemUserService.deleteSystemUsers(record.systemUserId)

        notify.success('删除用户成功', {
          title: '操作成功',
        })

        fetchData()
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : '删除用户失败'
        notify.error(errorMessage, {
          title: '操作失败',
        })
      } finally {
        loading.value = false
      }
    },
  })
}

/** 提交表单 */
const handleSubmit = async () => {
  try {
    loading.value = true
    const submitData = filterEmptyValue(formData) as SystemUsersRequest
    if (isAdd.value) {
      await systemUserService.createSystemUsers(submitData)
      notify.success('新增用户成功', {
        title: '操作成功',
      })
    } else {
      await systemUserService.modifySystemUsers(submitData)
      notify.success('修改用户成功', {
        title: '操作成功',
      })
    }

    dialogVisible.value = false
    fetchData() // 刷新列表
    return true
  } catch (error) {
    const errorMessage =
      error instanceof Error ? error.message : `${isAdd.value ? '新增' : '修改'}用户失败`
    notify.error(errorMessage, {
      title: '操作失败',
    })
    return false
  } finally {
    loading.value = false
  }
}

/** 取消操作 */
const handleCancel = () => {
  dialogVisible.value = false
  resetForm()
}

/** 重置表单 */
const resetForm = () => {
  // 重置表单校验状态
  formRef.value?.resetFields()

  // 重置 formData 的所有字段为初始值
  Object.assign(formData, {
    systemUserId: '',
    account: '',
    password: '',
    name: '',
    realName: '',
    avatar: '',
    email: '',
    phone: '',
    birthday: '',
    sex: 1,
    availableDrawCount: 0,
    roleId: '',
  })
}

/** 分页变化处理 */
const handlePaginationChange = (newPagination: typeof pagination.value) => {
  pagination.value = newPagination
  fetchData(currentSearchParams.value) // 使用保存的搜索条件
}

/** 查看详情 */
const handleDetail = async (record: SystemUsersResponse) => {
  try {
    loading.value = true
    const res = await systemUserService.getSystemUsersById(record.systemUserId)

    // 更新详情数据
    detailInfo.value = res

    detailVisible.value = true
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : '获取用户详情失败'
    notify.error(errorMessage, {
      title: '操作失败',
    })
  } finally {
    loading.value = false
  }
}

/** 重置密码 */
const handleResetPassword = (record: SystemUsersResponse) => {
  Modal.warning({
    title: '重置密码',
    content: `确定要重置用户 "${record.name}" 的密码吗？`,
    okText: '确定',
    cancelText: '取消',
    hideCancel: false,
    async onOk() {
      try {
        loading.value = true
        await systemUserService.resetPassword({
          systemUserId: record.systemUserId,
          newPassword: defaultPassword,
        })
        notify.success('密码重置成功', {
          title: '操作成功',
        })
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : '密码重置失败'
        notify.error(errorMessage, {
          title: '操作失败',
        })
      } finally {
        loading.value = false
      }
    },
  })
}

/** 修改状态 */
const handleModifyStatus = (record: SystemUsersResponse) => {
  const newStatus = record.status === 1 ? 2 : 1
  const actionText = record.status === 1 ? '停用' : '启用'

  Modal.warning({
    title: `确认${actionText}`,
    content: `确定要${actionText}用户 "${record.name}" 吗？`,
    okText: '确定',
    cancelText: '取消',
    hideCancel: false,
    async onOk() {
      try {
        loading.value = true
        await systemUserService.modifyStatus({
          systemUserId: record.systemUserId,
          status: newStatus,
        })
        notify.success(`${actionText}成功`, {
          title: '操作成功',
        })
        fetchData() // 刷新列表
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : `${actionText}失败`
        notify.error(errorMessage, {
          title: '操作失败',
        })
      } finally {
        loading.value = false
      }
    },
  })
}

// 修改获取角色下拉框数据的方法
const fetchRoleOptions = async (roleKey?: string) => {
  try {
    roleLoading.value = true
    const res = await roleService.getRoleBox({ roleKey })
    roleOptions.value = res
  } catch {
    notify.error('获取角色列表失败')
  } finally {
    roleLoading.value = false
  }
}

// 添加角色搜索处理方法
const handleRoleSearch = (searchValue: string) => {
  if (searchValue.trim()) {
    fetchRoleOptions(searchValue)
  } else {
    fetchRoleOptions()
  }
}

// 初始加载
fetchData()

// 在组件挂载时获取角色下拉框数据
onMounted(() => {
  fetchRoleOptions()
})
</script>
